package cn.com.huzo.service.purchase.impl;

import cn.com.huzo.model.entities.purchase.PoLinesEntity;
import huzofw.model.entities.paginator.Paginator;
import huzofw.service.impl.GenericManagerImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.com.huzo.service.purchase.PoLinesManager;
import cn.com.huzo.service.purchase.PoLinesMrpLinesManager;
import cn.com.huzo.service.purchase.PoLinesMrpFeedingLinesManager;
import cn.com.huzo.repository.purchase.PoLinesRepository;
import cn.com.huzo.repository.purchase.PoLinesMrpFeedingRepository;
import cn.com.huzo.repository.purchase.PoLinesMrpRepository;

/**
 * 采购订单明细管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("PoLinesManager")
public class PoLinesManagerImpl extends GenericManagerImpl<PoLinesEntity, String>
        implements PoLinesManager {

    @Resource(name = "PoLinesRepository")
    private PoLinesRepository _dao_lines;

    @Resource(name = "PoLinesMrpRepository")
    private PoLinesMrpRepository _dao_lines_mrp;

    @Resource(name = "PoLinesMrpFeedingRepository")
    private PoLinesMrpFeedingRepository _dao_lines_mrp_feeding;

    @Resource(name = "PoLinesMrpLinesManager")
    private PoLinesMrpLinesManager _manager_lines_mrp_lines;

    @Resource(name = "PoLinesMrpFeedingLinesManager")
    private PoLinesMrpFeedingLinesManager _manager_lines_mrp_feedinglines;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchForPage(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        Long offset = (long) (MapUtils.getInteger(criterion, "Limit") * (MapUtils.getInteger(criterion, "PageIndex") - 1));
        long total = _dao_lines.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<PoLinesEntity> itemList = _dao_lines.fetchForPage(criterion);
            Paginator<PoLinesEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchForPageByPoNo(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        Long offset = (long) (MapUtils.getInteger(criterion, "Limit") * (MapUtils.getInteger(criterion, "PageIndex") - 1));
        long total = _dao_lines.fetchForCountByPoNo(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<PoLinesEntity> itemList = _dao_lines.fetchForPageByPoNo(criterion);
            Paginator<PoLinesEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public List<String> fetchAllSelectedLines(Map<String, Object> criterion) throws Exception {
        return _dao_lines.fetchAllSelectedLines(criterion);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> updateLines(Long headerId, Long updateddBy,
            Long currentUserId, Integer limit, Integer pageIndex, String orderBy, List<PoLinesEntity> itemList) throws Exception {
        Integer rowsAffected = _dao_lines.batchUpdate(itemList);

        if (rowsAffected > 0) {
            _dao_lines.syncUpdateMrpLinesMaterialSpecification(itemList);  // 同步更新调达表对应材料的规格
            // 审计日志
            writeAuditLog(updateddBy, "采购管理→采购订单明细", "订单ID：" + headerId, "更新");
        }

        // 第二步：返回删除后的数据
        Map<String, Object> _result = new HashMap();

        Map<String, Object> criterion = new HashMap();
        criterion.put("HeaderId", headerId);
        criterion.put("PageIndex", pageIndex);  // 当前明细页
        criterion.put("Limit", limit);
        criterion.put("OrderBy", orderBy);

        _result.put("PoLinesList", this.fetchForPage(criterion));
        _result.put("PoMaterialList", _dao_lines.fetchPoMaterialList(headerId));

        _result.put("Success", true);

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> updateRowMaterial(Long headerId, Long updatedBy, Long currentUserId,
            Integer limit02, Integer limit03, Integer limit04, Integer pageIndex04, String orderBy,
            List<PoLinesEntity> itemList) throws Exception {
        Map<String, Object> _result = new HashMap();

        // 第一步：同步更新 BOM材料
        //_dao_lines.syncUpdateMainBomLinesMaterial(itemList);
        // 第二步：更新订单材料明细
        Integer rowsAffected = _dao_lines.updateRowMaterial(itemList);
        if (rowsAffected > 0) {
            // 审计日志
            writeAuditLog(updatedBy, "采购管理→采购订单明细", "订单ID：" + headerId, "更改材料");

            // 第三步：返回更新后的数据
            Map<String, Object> criterion = new HashMap();
            criterion.put("HeaderId", headerId);
            criterion.put("PageIndex", pageIndex04);  // 当前明细页
            criterion.put("Limit", limit04);
            criterion.put("OrderBy", orderBy);

            _result.put("PoLinesList", this.fetchForPage(criterion));
            _result.put("PoMaterialList", _dao_lines.fetchPoMaterialList(headerId));

            criterion.replace("PageIndex", 1);  // 当前为第一页
            // 得到引入的调达表明细信息
            criterion.replace("Limit", limit02);
            criterion.put("OrderBy", "");
            _result.put("LinesMrpList", _dao_lines_mrp.fetchByHeaderId(headerId));
            _result.put("LinesMrpLinesList", _manager_lines_mrp_lines.fetchForPage(criterion));

            // 得到引入的补料单信息
            criterion.replace("Limit", limit03);
            _result.put("LinesMrpFeedingList", _dao_lines_mrp_feeding.fetchByHeaderId(headerId));
            _result.put("LinesMrpFeedingLinesList", _manager_lines_mrp_feedinglines.fetchForPage(criterion));

            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> deleteLines(String linesId, Long headerId,
            Long deletedBy, Long currentUserId,
            Integer limit02, Integer limit03,
            Integer limit04, Integer pageIndex04, String orderBy) throws Exception {
        // 第一步：删除明细
        Integer rowsAffected = _dao_lines.delete(linesId);
        if (rowsAffected > 0) {
            // 审计日志
            writeAuditLog(deletedBy, "采购管理→采购订单明细", "订单ID：" + headerId, "删除");
        }

        // 第二步：返回删除后的数据
        Map<String, Object> _result = new HashMap();

        Map<String, Object> criterion = new HashMap();
        criterion.put("HeaderId", headerId);
        criterion.put("PageIndex", pageIndex04);  // 当前明细页
        criterion.put("Limit", limit04);
        criterion.put("OrderBy", orderBy);

        _result.put("PoLinesList", this.fetchForPage(criterion));
        _result.put("PoMaterialList", _dao_lines.fetchPoMaterialList(headerId));

        criterion.replace("PageIndex", 1);  // 当前为第一页
        // 得到引入的调达表明细信息
        criterion.replace("Limit", limit02);
        criterion.put("OrderBy", "");
        _result.put("LinesMrpList", _dao_lines_mrp.fetchByHeaderId(headerId));
        _result.put("LinesMrpLinesList", _manager_lines_mrp_lines.fetchForPage(criterion));

        // 得到引入的补料单信息
        criterion.replace("Limit", limit03);
        _result.put("LinesMrpFeedingList", _dao_lines_mrp_feeding.fetchByHeaderId(headerId));
        _result.put("LinesMrpFeedingLinesList", _manager_lines_mrp_feedinglines.fetchForPage(criterion));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> batchDeleteLines(Long headerId,
            Long deletedBy, Long currentUserId,
            Integer limit02, Integer limit03,
            Integer limit04, Integer pageIndex04, String orderBy,
            List<PoLinesEntity> itemList) throws Exception {
        // 第一步：删除明细
        Integer rowsAffected = _dao_lines.batchDelete(itemList);

        if (rowsAffected > 0) {
            // 第二步：删除空引用的调达及补料单
            _dao_lines.delete_for_sync_lines(headerId);
            // 审计日志
            writeAuditLog(deletedBy, "采购管理→采购订单明细", "订单ID：" + headerId, "删除");
        }
        // 第三步：返回删除后的数据
        Map<String, Object> _result = new HashMap();

        Map<String, Object> criterion = new HashMap();
        criterion.put("HeaderId", headerId);
        criterion.put("PageIndex", pageIndex04);  // 当前明细页
        criterion.put("Limit", limit04);
        criterion.put("OrderBy", orderBy);

        _result.put("PoLinesList", this.fetchForPage(criterion));
        _result.put("PoMaterialList", _dao_lines.fetchPoMaterialList(headerId));

        criterion.replace("PageIndex", 1);  // 当前为第一页
        // 得到引入的调达表明细信息
        criterion.replace("Limit", limit02);
        criterion.put("OrderBy", "");
        _result.put("LinesMrpList", _dao_lines_mrp.fetchByHeaderId(headerId));
        _result.put("LinesMrpLinesList", _manager_lines_mrp_lines.fetchForPage(criterion));

        // 得到引入的补料单信息
        criterion.replace("Limit", limit03);
        _result.put("LinesMrpFeedingList", _dao_lines_mrp_feeding.fetchByHeaderId(headerId));
        _result.put("LinesMrpFeedingLinesList", _manager_lines_mrp_feedinglines.fetchForPage(criterion));

        _result.put("Success", true);

        return _result;
    }
}
